#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>             /* exit() */
#include <strings.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <pthread.h>
#include <signal.h>

#include "user.h"
#include "clienthandler.h"

#define MAXATTENTE 15

static pthread_mutex_t verrou;

void exit_handler(int sig);

int serversock;

int
main(int argc, char *argv[])
{
    signal(SIGINT, exit_handler);

        pthread_t serviceClient;

    int clientsock;
    struct sockaddr_in echoserver, echoclient;
    unsigned int clientlen = sizeof(echoclient);

        user_list* newUser;

    if (argc != 2)
    {
        fprintf(stderr, "USAGE: echoserver <port>\n");
        exit(1);
    }
    /* Creer le socket TCP */
    if ((serversock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
    {
        perror("Probleme socket\n");
        exit(-2);
    }
    memset(&echoserver, 0, sizeof(echoserver)); /* Clear struct */
    echoserver.sin_family = AF_INET;    /* Internet/IP */
    echoserver.sin_addr.s_addr = htonl(INADDR_ANY);     /* Incoming addr */
    echoserver.sin_port = htons(atoi(argv[1])); /* Server port */

    if (bind(serversock, (struct sockaddr *) &echoserver, sizeof(echoserver)) < 0)
    {
        printf("Probleme bind %s\n", argv[1]);
        exit(-3);
    }
    if (listen(serversock, MAXATTENTE) < 0)
    {
        printf("Probleme d'ecoute\n");
        exit(-4);
    }
    
    initClientHandler();
    
    for (;;)
    {
        if ((clientsock = accept(serversock, (struct sockaddr *) &echoclient, &clientlen)) <= 0)
        {
            printf("La connexion n'a pas pu etre acceptee.\n");
        }
        
        fprintf(stdout, "%d: Client connecté : %s\n", clientsock, inet_ntoa(echoclient.sin_addr));
        
        newUser = registerClient(clientsock);
        
        pthread_create(&serviceClient, NULL, (void *) &handleClient, (void *) newUser);
    }

}


void
exit_handler(int sig)
{
    printf("Fermeture du socket.\n");
    close(serversock);
    exit(0);
}

